package com.test.test

import android.annotation.SuppressLint
import android.content.Context
import android.os.Bundle
import android.util.Log
import android.view.ViewGroup
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.viewpager2.adapter.FragmentStateAdapter
import androidx.viewpager2.widget.ViewPager2
import com.test.test.databinding.ActivityMainBinding

class MainActivity : AppCompatActivity() {
    private lateinit var mBinding: ActivityMainBinding
    private var fragments: MutableList<Fragment> = mutableListOf()
    private lateinit var curFragment: Fragment

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mBinding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(mBinding.root)
        initView()
        initEvent()
    }

    private fun initView(){
        fragments.add(FirstFragment())
        val secondFragment = SecondFragment()
        //将第二个Fragment中的垂直滑动距离传出进行设置tab的滑动
        secondFragment.setOnRvScrollListener {
            if(it < 0) mBinding.slTest.scrollBy(0, -it.toInt())
            //在下拉刷新时禁用上滑隐藏，手动上推到指定位置后启用
            slEnable = mBinding.vpTest.y.toInt() == dip2px(this,8f)
        }
        fragments.add(secondFragment)
        fragments.add(ThirdFragment())
        curFragment = fragments[0]
        mBinding.apply {
            vpTest.apply {
                //设置adapter显示Fragment
                adapter = VpFragmentAdapter(this@MainActivity,fragments)
                //ViewPager2缓存
                offscreenPageLimit = fragments.size
            }
        }

    }
    private fun initEvent(){
        mBinding.vpTest.registerOnPageChangeCallback(OnPageChangeCallback())
        //最外层ScrollView滑动到顶/到底监听
        mBinding.slTest.setOnScrollEndListener {
            Log.d("Main:", "scrollEnd: $it")
            mBinding.vpTest.apply {
                isUserInputEnabled = when(it){
                    //当上滑后（下端触底）不可左右切换，此处可改为仅下滑后可切换（上端触顶）
                    VerticalScrollView.flagBottom -> {
                        false
                    }
                    else -> true
                }
            }
            //下拉刷新仅下拉到顶后启用
            mBinding.srlTest.setEnableRefresh(it == VerticalScrollView.flagTop)
        }

    }

    /**
     * 左右滑动的fragmentAdapter
     */
    private inner class VpFragmentAdapter(fragment: FragmentActivity, private val mFragments: List<Fragment>) : FragmentStateAdapter(fragment) {
        override fun createFragment(position: Int): Fragment {
            return mFragments[position]
        }
        override fun getItemCount(): Int {
            return mFragments.size
        }
    }

    /**
     * 页面切换事件回调
     */
    private inner class OnPageChangeCallback: ViewPager2.OnPageChangeCallback(){
        @SuppressLint("ClickableViewAccessibility")
        override fun onPageSelected(position: Int) {
            super.onPageSelected(position)
            when(position){
                0 -> {
                    slEnable = false
                }
                1 -> {
                    slEnable = true
                }
                2 -> {
                    slEnable = false
                }
            }
        }
    }

    /**
     * 设置是否可上滑
     */
    var slEnable: Boolean = false
        set(value) {
        field = value
        val params: ViewGroup.LayoutParams = mBinding.vpTest.layoutParams
        //实际上是增加了viewPager2的高度，增加了一个tab的高度，使外层ScrollView可上滑一个tab的位置，此处可替换为测量值
        if(value) params.height = dip2px(this@MainActivity, 677f)
        else params.height = dip2px(this@MainActivity, 600f)
        mBinding.vpTest.layoutParams = params
    }

    /**
     * dp转px
     */
    private fun dip2px(context: Context, dpValue: Float): Int {
        val scale = context.resources.displayMetrics.density
        return (dpValue * scale + 0.5f).toInt()
    }
}